package luj.tool.jnproxyan.framework.lujnet.receive;

import io.netty.buffer.ByteBuf;
import luj.net.api.server.FrameDataReceiver;
import luj.tool.jnproxyan.framework.lujnet.ConnState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.google.common.base.Preconditions.checkState;

@Component
final class Recv41RequestHeader implements FrameDataReceiver {

  @Override
  public Result receive(Context ctx) throws Exception {
    ByteBuf frameBuf = ctx.getLastFrame();
    ConnState connState = ctx.getConnectionState();

    int version = frameBuf.readByte();
    int cmd = frameBuf.readByte();
    connState.setCmd(cmd);

    int reserved = frameBuf.readByte();
    int addrType = frameBuf.readByte();

    if (addrType == IPV4) {
      return ctx.then()
          .waitBytes(4)
          .nextReceiver(_receiveIp);
    }

    if (addrType == IPV6) {
      return ctx.then()
          .waitBytes(16)
          .nextReceiver(_receiveIp);
    }

    checkState(addrType == DOMAIN_NAME, addrType);

    return ctx.then()
        .waitBytes(1)
        .nextReceiver(_receiveDomain);
  }

  private static final int IPV4 = 0x01;
  private static final int DOMAIN_NAME = 0x03;
  private static final int IPV6 = 0x04;

  @Autowired
  Recv42RequestAddrIp _receiveIp;

  @Autowired
  Recv43RequestAddrDomainLen _receiveDomain;
}
